<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 头部区域 -->
    <div class="bg-white shadow-sm">
      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-800">
              编辑标签
            </h1>
            <p class="text-gray-600 mt-1">
              修改标签信息
            </p>
          </div>
          <UButton
            color="gray"
            variant="outline"
            @click="goBack"
          >
            <UIcon
              name="i-heroicons-arrow-left"
              class="w-4 h-4 mr-2"
            />
            返回
          </UButton>
        </div>
      </div>
    </div>

    <!-- 表单区域 -->
    <div class="container mx-auto px-4 py-8">
      <div class="max-w-2xl mx-auto">
        <div
          v-if="loading"
          class="flex justify-center items-center h-64"
        >
          <UILoadingSpinner class="w-8 h-8 text-primary" />
        </div>

        <div
          v-else-if="!tagData"
          class="bg-white rounded-lg shadow-sm p-8 text-center"
        >
          <UIcon
            name="i-heroicons-exclamation-triangle"
            class="w-16 h-16 text-gray-400 mx-auto mb-4"
          />
          <p class="text-gray-500 text-lg">
            标签不存在
          </p>
        </div>

        <div
          v-else
          class="bg-white rounded-lg shadow-sm p-6"
        >
          <UForm
            :state="formData"
            class="space-y-6"
            @submit="handleSubmit"
          >
            <UFormGroup
              label="标签名称"
              name="name"
              required
            >
              <template #hint>
                <span class="text-sm text-gray-500">标签名称不能为空</span>
              </template>
              <UInput
                v-model="formData.name"
                placeholder="请输入标签名称"
                :disabled="submitting"
                size="lg"
              />
            </UFormGroup>

            <UFormGroup
              label="排序"
              name="sortOrder"
            >
              <template #hint>
                <span class="text-sm text-gray-500">数值越小，排序越靠前</span>
              </template>
              <UInput
                v-model.number="formData.sortOrder"
                type="number"
                placeholder="请输入排序值"
                :disabled="submitting"
                size="lg"
              />
            </UFormGroup>

            <UFormGroup
              label="备注"
              name="remark"
            >
              <template #hint>
                <span class="text-sm text-gray-500">可选的备注信息</span>
              </template>
              <UTextarea
                v-model="formData.remark"
                placeholder="请输入备注信息"
                :rows="4"
                :disabled="submitting"
              />
            </UFormGroup>

            <div class="flex justify-end space-x-4 pt-6 border-t">
              <UButton
                color="gray"
                variant="outline"
                :disabled="submitting"
                size="lg"
                @click="goBack"
              >
                取消
              </UButton>
              <UButton
                type="submit"
                color="primary"
                variant="solid"
                :loading="submitting"
                size="lg"
              >
                <UIcon
                  name="i-heroicons-check"
                  class="w-4 h-4 mr-2"
                />
                更新标签
              </UButton>
            </div>
          </UForm>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { Tag } from '~/types/tag'

// 页面元数据
definePageMeta({
  layout: 'default',
  title: '编辑标签'
})

// 获取路由参数
const route = useRoute()
const tagId = route.params.id as string

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const tagData = ref<Tag | null>(null)

// 表单数据
const formData = ref({
  name: '',
  sortOrder: 0,
  remark: ''
})

// 返回上一页
const goBack = () => {
  navigateTo('/system/tag')
}

// 获取标签详情
const fetchTagDetail = async () => {
  if (!tagId) return

  loading.value = true

  try {
    const response = await $fetch(`/api/tag/tags/${tagId}`)

    if (response.success) {
      tagData.value = response.data
      formData.value = {
        name: response.data.name,
        sortOrder: response.data.sortOrder || 0,
        remark: response.data.remark || ''
      }
    } else {
      useToast().add({
        title: '获取标签详情失败',
        description: response.message || '请稍后重试',
        color: 'red'
      })
    }
  } catch (error) {
    console.error('获取标签详情失败:', error)
    useToast().add({
      title: '获取标签详情失败',
      description: '网络错误，请稍后重试',
      color: 'red'
    })
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formData.value.name) {
    useToast().add({
      title: '验证失败',
      description: '标签名称不能为空',
      color: 'red'
    })
    return
  }

  submitting.value = true

  try {
    const response = await $fetch(`/api/tag/tags/${tagId}`, {
      method: 'PUT',
      body: {
        name: formData.value.name,
        sortOrder: formData.value.sortOrder,
        remark: formData.value.remark
      }
    })

    if (response.success) {
      useToast().add({
        title: '更新成功',
        description: '标签已成功更新',
        color: 'green'
      })

      // 返回标签列表页
      navigateTo('/system/tag')
    } else {
      useToast().add({
        title: '更新失败',
        description: response.message || '请稍后重试',
        color: 'red'
      })
    }
  } catch (error) {
    console.error('更新标签失败:', error)
    useToast().add({
      title: '更新失败',
      description: '网络错误，请稍后重试',
      color: 'red'
    })
  } finally {
    submitting.value = false
  }
}

// 初始化
onMounted(() => {
  fetchTagDetail()
})
</script>
